<?php
/**
 * View_Form
 *
 * класс Form_Form позволяет работать с формами
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 2.1
 */

class Form_ViewForm extends Form_Form {

  protected $_fullWidth = null;
  protected $_leftWidth = null;
  protected $_helpUnderField = false;
  protected $_viewFormType = 'table';
  protected $_showAfterNameSymbols = true;
  

	public function __construct($arrSettings = array(), $objAR = null) {
	  Service_Debug::setDebug();
  	parent::__construct($arrSettings, $objAR);
  	if ($this->_leftWidth) {
  		if ($this->_class)  $this->_class .= ' strictWidth';
  		else  $this->_class = 'strictWidth';
  	}
  }

    /**
	 * Метод устанавливает свойство
	 *
	 * @param string $settingName
	 * @param mixed $settingValue
	 */
	public function setSetting($settingName, $settingValue, $additionalAllowedSettings = null) {
    switch ($settingName) {
    	case 'fullWidth':
    		$this->setFullWidth($settingValue);
    		break;
    	case 'leftWidth':
    		$this->setLeftWidth($settingValue);
    		break;
    		case 'showAfterNameSymbols':
    			$this->_showAfterNameSymbols = $settingValue;
    			break;
    	case 'helpUnderField':
    		$this->_helpUnderField = $settingValue;
    		break;
    	case 'viewFormType':
    		$this->_viewFormType = $settingValue;
    		break;
    	default:
    	  parent::setSetting($settingName, $settingValue, '"action", "enctype", "successMessage"');
			  break;
    }
	}

	/**
	 * Устанавливает общую ширину формы
	 *
	 * @param string $fullWidth
	 */
	private function setFullWidth($fullWidth) {
		$this->_fullWidth = $fullWidth;
	}
	/**
	 * Устанавливает ширину левого столбца
	 *
	 * @param string $leftWidth
	 */
	private function setLeftWidth($leftWidth) {
		$this->_leftWidth = $leftWidth;
	}

	/**
	 * Выводит тег <form> и иже с ним
	 *
	 */
	public function show($justPlain = false) {
		parent::show();
		$style = '';
			if ($this->_fullWidth) {
			  if (substr($this->_fullWidth, -1) == '%') $style = 'style="width:' . $this->_fullWidth  . ' !important;"';
			  else $style = 'style="width:' . $this->_fullWidth  . 'px !important;"';
			}
	  // Блочный вид (само поле находится под его названием)
		if ($this->_viewFormType == 'div') echo '<div ' . $style . '>';
		// Табличный вид (Поле сбоку от названия)
		else if (!$justPlain) echo '<table cellspacing="0" ' . $style . '>';
	}
	/**
	 * Выводит тег </form> и иже с ним
	 *
	 */
	public function close($justPlain = false) {
		if ($this->_viewFormType == 'div') echo '</div>';
		else if (!$justPlain) echo '</table>';
		parent::close();
	}

	/**
	 * Выводит то, что должно быть написано перед полем
	 *
	 * @param array $arrSettings
	 * @param string $fieldName
	 */
	public function showBeforeField(array $arrSettings = array(), $fieldName = null) {
		$styleLeft = '';
		$styleRight = '';
		if ($this->_viewFormType == 'div') {
			if (isset($arrSettings['text'])) {
				
				echo '<p class="fieldHeader">';
					if (isset($arrSettings['text'])) echo $arrSettings['text'];
					if (isset($arrSettings['text']) && $this->_showAfterNameSymbols) echo ':';
				  if (isset($arrSettings['text']) && isset($arrSettings['required']) && $this->_showAfterNameSymbols || isset($arrSettings['requiredOnly'])) echo '<span class="required">*</span>';
				  if (isset($arrSettings['help']) && !$this->_helpUnderField && !isset($arrSettings['afterHelp'])) echo '<br /><span class="help">' . $arrSettings['help'] . '</p>';
			  echo '</p>';
			}
		  echo '<p class="field">';
		} 
		else {
			if ($this->_leftWidth) {
			  $styleLeft = 'style="width:' . $this->_leftWidth  . 'px !important;"';
			  $styleRight = 'style="width:auto !important;"';
			}
			if (!isset($arrSettings['rowspan1'])) echo '<tr ' . (isset($arrSettings['hiddenRow']) && $arrSettings['hiddenRow'] ? 'style="display:none;"' : null) . '><td class="left" ' . $styleLeft . '>';
			else echo '<tr><td class="left" rowspan="' . $arrSettings['rowspan1'] . '" ' . $styleLeft . '>';
		  if (isset($arrSettings['text'])) echo $arrSettings['text'];
		  if (isset($arrSettings['text']) && isset($arrSettings['required'])) echo '<span class="required">*</span>';
		  if (isset($arrSettings['text'])) echo ':';
		  if (isset($arrSettings['help']) && !$this->_helpUnderField) echo '<p class="help">' . $arrSettings['help'] . '</p>';
			if (!isset($arrSettings['rowspan2'])) echo '</td><td class="right" '. $styleRight . '>';
			else echo '</td><td class="right" rowspan="' . $arrSettings['rowspan2'] . '" '. $styleRight . '>';
		}
	}
	
	/**
	 * Открывает одноколоночную часть
	 * 
	 */
	public function openOneColumnPart() {
		echo '<tr><td colspan="2">';
		$this->setSetting('viewFormType', 'div');
	}
	
	/**
	 * Закрывает одноколоночную часть
	 * 
	 */
	public function closeOneColumnPart() {
		echo '</td></tr>';
		$this->setSetting('viewFormType', 'table');
	}
	
	
	
	/**
	 * Выводит то, что должно быть написано после поля
	 *
	 * @param array $arrSettings
	 * @param string $fieldName
	 */
	public function showAfterField(array $arrSettings = array(), $fieldName = null) {
		if ($this->_viewFormType == 'div') {
			if (isset($arrSettings['help'])){
				if ($this->_helpUnderField) echo '<br /><span class="help">' . $arrSettings['help'] . '</span>';
				else {
					echo '<span class="popupTrigger" data-hover="1" data-tooltip-open="true">';
						echo '<img src="' . W_IMAGES . 'icons/icon-i-light.png" class="info-light" />';
						if (!empty($arrSettings['afterHelp'])) echo ' <span class="help afterHelp">' . $arrSettings['afterHelp'] . '</span>';
					echo '</span>';
					echo '<span class="popupBox" style="display:none;">';
						echo $arrSettings['help'];
					echo '</span>';
					
				}
			}
		  echo '</p>';
		}
		else {
		  if (isset($arrSettings['help']) && $this->_helpUnderField) {
		  	echo '<span class="help">' . $arrSettings['help'] . '</span>';
		  	//echo '<p class="help">' . $arrSettings['help'] . '</p>';
		  }
		  echo '</td></tr>';
		}
	}
	/**
	 * Формирует и выводит текстовый элемент ввода
	 *
	 * @param array $arrSettings
	 */
	public function textField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = '';
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		parent::textField($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}
	/**
	 * Формирует и выводит элемент select
	 *
	 * @param array $arrSettings
	 */
	public function selectField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = 'styled';
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		parent::selectField($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}
	
	/**
	 * Формирует и выводит элемент select
	 *
	 * @param array $arrSettings
	 */
	public function selectFieldNew(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = 'styled';
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		parent::selectFieldNew($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}

	/**
	 * Формирует и выводит каптчу
	 *
	 * @param array $arrSettings
	 */
	public function kaptchaField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = 'styled';
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
 		echo '<div id="kaptchaImageDiv">';
 		  echo '<img src="' . W_ABSPATH . 'auth/kaptcha" class="kaptcha" id="reg_crypt" alt="" />';
 		echo '</div>';
 		parent::textField($arrSettings, $fieldName);
    echo '<p class="enterCode"><a class="reg_crypt_change ajax" onclick="javascript:document.getElementById(\'reg_crypt\').src=\'' .  W_ABSPATH . 'auth/kaptcha/\'+Math.round(Math.random(0)*1000)+1">' . Service_Translate::getText('Обновить изображение') . '</a></p>';
    if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
		
	}

	/**
	 * Формирует и выводит элемент ввода файла
	 *
	 * @param array $arrSettings
	 */
	public function fileField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		if (isset($arrSettings['showImage'])) {
		  $folder = isset($arrSettings['showImage']['folder']) ? $arrSettings['showImage']['folder'] : null;
		  $file = isset($arrSettings['showImage']['file']) ? $arrSettings['showImage']['file'] : null;
		  $type = isset($arrSettings['showImage']['type']) ? $arrSettings['showImage']['type'] : '';
		  $style = isset($arrSettings['showImage']['style']) ? $arrSettings['showImage']['style'] : '';
		  if ($folder && $file) {
		    Service_Image::showSavedImage($folder, $file, $type, $style);
		    echo '<br />';
		  }
		  unset($arrSettings['showImage']);
		}
		parent::fileField($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}
	/**
	 * Формирует и выводит элемент textarea
	 *
	 * @param array $arrSettings
	 */
	public function textareaField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = 'standardTextarea';
		if (!empty($arrSettings['wideTextarea'])) {
			unset($arrSettings['wideTextarea']);
			if (!$onlyField) {
				$this->showBeforeField($arrSettings, $fieldName);
				$this->showAfterField($arrSettings, $fieldName);
			}
			$this->openOneColumnPart();
			parent::textareaField($arrSettings, $fieldName);
			$this->closeOneColumnPart();
		}
		else {
			if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
			parent::textareaField($arrSettings, $fieldName);
			if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
		}
	}

  /**
	 * Формирует и выводит текстовый элемент ввода пароля
	 *
	 * @param array $arrSettings
	 */
	public function passwordField(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!isset($arrSettings['class'])) $arrSettings['class'] = 'standardText';
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		parent::passwordField($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}
  /**
	 * Формирует и выводит чекбокс
	 *
	 * @param array $arrSettings
	 */
	public function checkbox(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		if (!$onlyField) $this->showBeforeField($arrSettings, $fieldName);
		parent::checkbox($arrSettings, $fieldName);
		if (!$onlyField) $this->showAfterField($arrSettings, $fieldName);
	}

  /**
	 * Формирует и выводит кнопку сабмит
	 *
	 * @param array $arrSettings
	 */
	public function submitButton(array $arrSettings = array(), $fieldName = null, $onlyField = false) {
		$styleLeft = '';
		$styleRight = '';
		if ($this->_leftWidth) {
		  $styleLeft = 'style="width:' . $this->_leftWidth  . 'px !important;"';
		  $styleRight = 'style="width:auto !important;"';
		}
		if (!isset($arrSettings['class']))
		  $arrSettings['class'] = 'standardSubmit blue-button';
		if (!$onlyField) {
			echo '<tr><td class="left" ' . $styleLeft . '>';
			  if (isset($arrSettings['text']))
			    echo $arrSettings['text'];
			echo '</td><td class="right" ' . $styleRight . '>';
		}
		parent::submitButton($arrSettings, $fieldName);
		if (!$onlyField) echo '</td></tr>';
	}

  /**
	 * Формирует и выводит Подзаголовок в форме
	 *
	 * @param array $arrSettings
	 */
	public function showHeader($headerText, $headerSize = 3) {
		echo '<tr><td colspan="2" class="header' . $headerSize . '">';
			echo '<h' . $headerSize . '>' . $headerText . '</h' . $headerSize . '>';
		echo '</td></tr>';
	}

  /**
	 * Выводит разделитель между строками
	 *
	 */
	public function showSeparator() {
		echo '<tr><td colspan="2" class="separator"></td></tr>';
	}

	/**
	 * Вывод всего массива в скрытые поля (для передачи с ледующую форму)
	 *
	 * @param unknown_type $arrFields
	 * @param unknown_type $name
	 */
	public static function showAllFields($arrFields, $name = '') {
		foreach ($arrFields as $key => $field) {
			if (is_array($field)) {
				if ($name != '') self::showAllFields($field, $name . '[' . $key . ']');
				else self::showAllFields($field, $key);
			}
			else $objHidden = new Form_Hidden(array('value' => $field), $name . ($name ? '[' : '') . $key . ($name ? ']' : ''), true);
		}
  }
}